#include <iostream>
#include <queue>
#include <cstring>

using namespace std;
const int N = 310, INF = 0x3f3f3f3f;
typedef pair<int, int> pii;
int m;
int dx[] = {0, 0, 1, -1};
int dy[] = {1, -1, 0, 0};
int t[N][N];
int dist[N][N];

int bfs()
{
    if(t[0][0] == INF) return 0;
    memset(dist , 0x3f , sizeof dist);
    queue<pii>q;
    q.push({0 , 0});
    dist[0][0] = 0;
    while(q.size())
    {
        auto a = q.front(); q.pop();
        int i = a.first , j = a.second;
        for(int k = 0;k < 4;k++)
        {
            int x = i + dx[k] , y = dy[k] + j;
            if(x < 0 || y < 0) continue;
            if(dist[x][y] != INF) continue;
            if(dist[i][j] + 1 >= t[x][y]) continue;

            dist[x][y] = dist[i][j] + 1;
            if(t[x][y] == INF) return dist[x][y];
            q.push({x , y});
        }
    }
    return -1;
}
int main()
{
    cin >> m;
    memset(t , 0x3f , sizeof t);
    for(int i = 1;i <= m;i ++)
    {
        int x , y , z; cin >> x >> y >> z;
        t[x][y] = min(t[x][y] , z);
        for(int k = 0;k < 4;k ++)
        {
            int i = x + dx[k] , j = y + dy[k];
            if(i < 0 || j < 0) continue;

            t[i][j] = min(t[i][j] , z);
        }
    }
    cout << bfs() << endl;
    return 0;
}